/*
 * Copyright 2006 - 2007 - Chris Maki
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.theserverside.blog.util;

import java.util.Formatter;
import java.util.List;

import com.theserverside.blog.model.BlogPost;
import com.theserverside.blog.model.Comment;

public class BlogModelPrinter {

    public static final int TOP_LEVEL_INDENT = 0;

    public static boolean printResults = true;
    
    public static void printBlogPosts(List<BlogPost> posts) {
        int i = 1;
        for (BlogPost blogPost : posts) {
            printBlogPost(blogPost, i++ );
        }
    }

    public static void printDetailedBlogPost(BlogPost blogPost) {
        System.out.println(blogPost);
    }
    
    public static void printBlogPost(BlogPost blogPost) {
        printBlogPost(blogPost, null);
    }
    
    protected static void printBlogPost(BlogPost blogPost, Integer i) {
        StringBuilder sb = new StringBuilder();
        Formatter f = new Formatter(sb);
        if (i != null) {
            f.format("Entry [%d]:", i);
        }        
        
        f.format("\ntitle: [%s]\nContent: [%s]\ntags: [%s]", blogPost.getTitle(), 
                blogPost.getContent(), blogPost.getTags());
        
        int commentCount = 1;
        for (Comment comment : blogPost.getComments()) {
            addComments(f, comment, TOP_LEVEL_INDENT, commentCount++);
        }

        if (printResults) {
            System.out.println(sb.toString());
        }
    }

    private static void addComments(Formatter f, Comment comment, int indentLevel, int commentCount) {
        String indent = buildIndentForLevel(indentLevel);
        f.format("\n%sComment: [%d.%d]\n%stitle \"%s\"\n%scomment [%s]\n%suuid: [%s]", indent, 
                indentLevel, commentCount, 
                indent, comment.getTitle(), 
                indent, comment.getContent(),
                indent, comment.getUuid());
        
        int nestedCommentCount = 1;
        int newIndent = indentLevel + 1;
        for (Comment c : comment.getChildren()) {
            addComments(f, c, newIndent, nestedCommentCount++);
        }
    }

    private static String buildIndentForLevel(int level) {
        StringBuilder indentString = new StringBuilder("\t");
        for (int y = 0; y < level; y++) {
            indentString.append("\t");
        }
        return indentString.toString();
    }
}
